package com.cskaoyan.utils;


import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 创建日期: 2022/08/25 16:50
 *
 * @author ciggar
 */
public class JDBCUtils {

    // 饿汉
    static Connection connection = null;

    public static String url = null;
    public static String username = null;
    public static String password = null;
    private static String driver = null;

    static {

        try {

            // 获取配置文件中的值
            Properties properties = new Properties();
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
            properties.load(fileInputStream);

            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");

            // 注册驱动
            // 自动注册驱动  SPI
            Class.forName(driver);

            // 获取连接

            connection = DriverManager.getConnection(url, username, password);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // 获取连接
    public static Connection getConnection(){

        return connection;

    }


    // 获取一个新的连接
    public static Connection getNewConnection(){

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }


    // 关闭资源
    public static void close(ResultSet resultSet, Statement statement,Connection connection){

        try {

            if (resultSet != null) resultSet.close();

            if (statement != null) statement.close();

            if (connection != null) connection.close();

        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}
